import { ApiResponse, getSearch as getSearchtype, Search } from '@/types/data'
import { RootThunkAction } from '@/types/store'
import request from '@/utils/request'
import { setHistory } from '@/utils/searchOption'

// 模糊搜索
// RootThunkAction
export const suggestionApi = (q:string):RootThunkAction => {
  return async (dispatch) => {
    //  调用接口
    if (q.length === 0) {
      dispatch({ type: 'search/option', payload: [] })
    } else {
      const res = await request.get<ApiResponse<{options:Search}>>('/suggestion', {
        params: {
          q
        }
      })
      dispatch({ type: 'search/option', payload: res.data.data.options })
    }
  }
}

// 添加到历史搜索
export const addHistory = (q:string):RootThunkAction => {
  return async (dispatch, getState) => {
    // 获取到原来的histories
    let histories = getState().search.searchHistory
    // 1. 不允许有重复的历史记录, 先删除原来历史记录中的keyword
    histories = histories.filter((item) => item !== q)
    // 添加keyword
    histories = [q, ...histories]
    // 2. 最多显示10条
    if (histories.length > 10) {
      histories = histories.slice(0, 10)
    }
    setHistory(histories)
    dispatch({ type: 'search/addHistory', payload: histories })
  }
}
// 添加到历史搜索
export const clearHistories = ():RootThunkAction => {
  return async (dispatch) => {
    setHistory([])
    dispatch({ type: 'search/addHistory', payload: [] })
  }
}
// 获取搜索内容
export const getSearch = (q:string, page:number = 1, per_page:number = 10):RootThunkAction => {
  return async (dispatch) => {
    const res = await request.get<ApiResponse<getSearchtype>>('/search', {
      params: {
        page,
        per_page,
        q
      }
    })
    dispatch({ type: 'search/getSearch', payload: res.data.data })
  }
}
